package com.lenovo.smarttraffic.ui.activity.stage3;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.NotificationCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.database.SensorDataDB;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.Utils;

import org.litepal.LitePal;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.NOTIFICATION_SERVICE;

public class EnvIndicateActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar mToolbar;
    private DrawerLayout mDrawer;
    private NavigationView navigationView;

    private TextView ts_settings;

    private RecyclerView rvView;
    private EnvIndicateAdapter adapter;

    private Handler handler = new Handler();

    private Gson gson = new Gson();

    public static Map<String, Object> data = new HashMap<>();

    private SharedPreferences preferences;

    @Override
    protected int getLayout() {
        return R.layout.activity_env_indicate;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        preferences = getSharedPreferences(Constant.THRESHOLD, MODE_PRIVATE);
        initView();
    }

    public void initView() {
        mToolbar = findViewById(R.id.toolbar_three);

        mDrawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ts_settings = findViewById(R.id.ts_settings);
        ts_settings.setOnClickListener(v -> startActivity(new Intent(this, EnvThresholdActivity.class)));

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        toggle.syncState();
        mDrawer.addDrawerListener(toggle);

        rvView = findViewById(R.id.rvView);

        rvView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        adapter = new EnvIndicateAdapter(this, data);
        rvView.setAdapter(adapter);

        runnable.run();
        refresh();
    }

    private void refresh() {
        handler.postDelayed(() -> {
            runnable.run();
            refresh();
        }, 3000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            HttpUtils.post("get_all_sense",
                    new HttpUtils().setParam("UserName", MainActivity.userName), response -> {
                        data.clear();
                        Map<String, Object> getMap = gson.fromJson(response.toString(), Map.class);
                        getMap.remove("RESULT");
                        getMap.remove("ERRMSG");
                        data.putAll(getMap);
                        //追加数据，进行道路状况添加
                        HttpUtils.post("get_road_status"
                                , new HttpUtils().setParam("RoadId", 1), response1 -> {
                                    //进行更新显示
                                    Map map = new Gson().fromJson(response1.toString(), Map.class);
                                    data.put("roadState", map.get("Status"));
                                    adapter.notifyDataSetChanged();
                                    //限制20条数据
                                    List<SensorDataDB> dbList = LitePal.order("date desc").find(SensorDataDB.class);
                                    if (dbList.size() > 19) {
                                        //将前19保留
                                        for (int i = 0; i < dbList.size(); i++) {
                                            if (i > 19) {
                                                dbList.get(i).delete();
                                            }
                                        }
                                    }
                                    new SensorDataDB(new Date(),
                                            data.get("LightIntensity").toString(),
                                            data.get("humidity").toString(),
                                            data.get("temperature").toString(),
                                            data.get("pm2.5").toString(),
                                            data.get("roadState").toString(),
                                            data.get("co2").toString()).save();
                                });
                    });
        }
    };


    @Override
    public void onBackPressedSupport() {
        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawer(GravityCompat.START);
        } else {
            finish();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.realtime_show:
                startActivity(new Intent(this, RealTimeActivity.class));
                break;
            case R.id.threshold_set:
                startActivity(new Intent(this, EnvThresholdActivity.class));
                break;
            case R.id.realtime_env:
                startActivity(new Intent(this, RealEnvActivity.class));
                break;
            case R.id.weather_info:
                startActivity(new Intent(this, WeatherActivity.class));
                break;
            case R.id.life_helper:
                startActivity(new Intent(this, LifeHelperActivity.class));
                break;
            case R.id.weather_forecast:
                startActivity(new Intent(this, ForecastActivity.class));
                break;
        }

        mDrawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

class EnvIndicateAdapter extends RecyclerView.Adapter<EnvIndicateAdapter.ViewHolder> {

    private Context context;
    private Map<String, Object> data;

    private SharedPreferences preferences;

    private NotificationManager manager;

    EnvIndicateAdapter(Context context, Map<String, Object> data) {
        this.context = context;
        this.data = data;
        this.preferences = context.getSharedPreferences(Constant.THRESHOLD, Context.MODE_PRIVATE);
        this.manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_env_indicate, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        switch (position) {
            case 0:
                int temperature = Double.valueOf(data.get("temperature").toString()).intValue();
                refresh(holder, "温度", "temperature", needAlert(temperature, position), position);
                break;
            case 1:
                int humidity = Double.valueOf(data.get("humidity").toString()).intValue();
                refresh(holder, "湿度", "humidity", needAlert(humidity, position), position);
                break;
            case 2:
                int LightIntensity = Double.valueOf(data.get("LightIntensity").toString()).intValue();
                refresh(holder, "光照", "LightIntensity", needAlert(LightIntensity, position), position);
                break;
            case 3:
                int co2 = Double.valueOf(data.get("co2").toString()).intValue();
                refresh(holder, "CO2", "co2", needAlert(co2, position), position);
                break;
            case 4:
                int pm2 = Double.valueOf(data.get("pm2.5").toString()).intValue();
                refresh(holder, "PM2.5", "pm2.5", needAlert(pm2, position), position);
                break;
            case 5:
                int roadState = Double.valueOf(data.get("roadState").toString()).intValue();
                refresh(holder, "道路状态", "roadState", needAlert(roadState, position), position);
                break;
        }
    }

    private boolean needAlert(int value, int position) {
        return value > getTsLevel(position);
    }

    private int getTsLevel(int type) {
        boolean auto_alert = preferences.getBoolean(Constant.AUTO_ALERT, false);
        int ts_auto = 1;
        String key = "";
        switch (type) {
            case 0:
                ts_auto = 10;
                key = Constant.ts_temp;
                break;
            case 1:
                ts_auto = 30;
                key = Constant.ts_hum;
                break;
            case 2:
                ts_auto = 1000;
                key = Constant.ts_light;
                break;
            case 3:
                ts_auto = 30;
                key = Constant.ts_co2;
                break;
            case 4:
                ts_auto = 120;
                key = Constant.ts_pm25;
                break;
            case 5:
                ts_auto = 3;
                key = Constant.ts_road;
                break;
        }

        return auto_alert ? ts_auto : Utils.parseInt(preferences.getString(key, "1"), ts_auto);
    }

    private void refresh(@Nullable ViewHolder holder, String title, String value, boolean needAlert, int pos) {
        holder.title.setText(title);

        int curr_value = Utils.parseInt(data.get(value).toString().replace(".0", ""));
        holder.value.setText(curr_value + "");

        if (!preferences.getBoolean(Constant.AUTO_ALERT, true)) {
            DrawableCompat.setTint(holder.parent.getBackground(), context.getResources().getColor(R.color.Yellow));
        } else {
            DrawableCompat.setTint(holder.parent.getBackground(), context.getResources().getColor((needAlert ? R.color.Red : R.color.Green)));

            int ts_level = getTsLevel(pos);
            if (manager != null && curr_value > ts_level) {
                NotificationCompat.Builder builder;
                int channelId = 1;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Android 8.0适配
                    NotificationChannel channel = new NotificationChannel(String.valueOf(channelId),
                            "阈值警告", NotificationManager.IMPORTANCE_HIGH);
                    manager.createNotificationChannel(channel);
                    builder = new NotificationCompat.Builder(context, String.valueOf(channelId));
                } else {
                    builder = new NotificationCompat.Builder(context);
                }
                RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notify_env);
                remoteViews.setTextViewText(R.id.notify_title, title + "报警");
                remoteViews.setTextViewText(R.id.notify_value, "阈值" + ts_level + "，当前值" + data.get(value).toString().replace(".0", ""));
                builder.setContentTitle(title + "报警")
                        .setContentText("阈值" + ts_level + "，当前值" + data.get(value).toString().replace(".0", ""))
                        .setCustomContentView(remoteViews)
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.car3)    //通知显示的小图标，只能用alpha图层的图片进行设置
                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.car3));

                Notification notification = builder.build();
                //channelId为本条通知的id
                manager.notify(channelId, notification);
            }
        }

        holder.parent.setOnClickListener(v -> {
            Intent intent = new Intent(v.getContext(), RealTimeActivity.class);
            intent.putExtra("pos", pos);
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout parent;
        TextView title, value;

        private ViewHolder(View itemView) {
            super(itemView);

            parent = itemView.findViewById(R.id.item_parent);
            title = itemView.findViewById(R.id.title);
            value = itemView.findViewById(R.id.value);
        }
    }
}
